﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 进货退货服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class ReturnordersService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Returnorders> _returnordersRep;
    private readonly SysFileService _sysFileService;
    private readonly ISqlSugarClient _sqlSugarClient;

    public ReturnordersService(SqlSugarRepository<Returnorders> returnordersRep, SysFileService sysFileService, ISqlSugarClient sqlSugarClient)
    {
        _returnordersRep = returnordersRep;
        _sysFileService = sysFileService;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询进货退货 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询进货退货")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<ReturnordersOutput>> Page(PageReturnordersInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _returnordersRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.ReturnCode.Contains(input.Keyword) || u.Contact.Contains(input.Keyword) || u.IncomingPeopleId.Contains(input.Keyword) || u.ReturnedGoods.Contains(input.Keyword) || u.Reviewer.Contains(input.Keyword) || u.Remarks.Contains(input.Keyword) || u.UploadFile.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ReturnCode), u => u.ReturnCode.Contains(input.ReturnCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.IncomingPeopleId), u => u.IncomingPeopleId.Contains(input.IncomingPeopleId.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ReturnedGoods), u => u.ReturnedGoods.Contains(input.ReturnedGoods.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Reviewer), u => u.Reviewer.Contains(input.Reviewer.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remarks), u => u.Remarks.Contains(input.Remarks.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UploadFile), u => u.UploadFile.Contains(input.UploadFile.Trim()))
            .WhereIF(input.Audit != null, u => u.Audit == input.Audit)
            .WhereIF(input.ReturnTimeRange?.Length == 2, u => u.ReturnTime >= input.ReturnTimeRange[0] && u.ReturnTime <= input.ReturnTimeRange[1])
            .WhereIF(input.IncomingOrdersId != null, u => u.IncomingOrdersId == input.IncomingOrdersId)
            .WhereIF(input.VendorId != null, u => u.VendorId == input.VendorId)
            .WhereIF(input.ContactInformation != null, u => u.ContactInformation == input.ContactInformation)
            .WhereIF(input.DepartmentId != null, u => u.DepartmentId == input.DepartmentId)
            .WhereIF(input.UserId != null, u => u.UserId == input.UserId)
            .WhereIF(input.OrganizationsId != null, u => u.OrganizationsId == input.OrganizationsId)
            .WhereIF(input.MakeDataRange?.Length == 2, u => u.MakeData >= input.MakeDataRange[0] && u.MakeData <= input.MakeDataRange[1])
            .WhereIF(input.ReviewTimeRange?.Length == 2, u => u.ReviewTime >= input.ReviewTimeRange[0] && u.ReviewTime <= input.ReviewTimeRange[1])
            .LeftJoin<Incomingorders>((u, incomingOrders) => u.IncomingOrdersId == incomingOrders.Id)
            .LeftJoin<Vendor>((u, incomingOrders, vendor) => u.VendorId == vendor.Id)
            .LeftJoin<department>((u, incomingOrders, vendor, department) => u.DepartmentId == department.Id)
            .LeftJoin<UserInfo>((u, incomingOrders, vendor, department, user) => u.UserId == user.Id)
            .LeftJoin<Organizations>((u, incomingOrders, vendor, department, user, organizations) => u.OrganizationsId == organizations.Id)
            .Select((u, incomingOrders, vendor, department, user, organizations) => new ReturnordersOutput
            {
                Id = u.Id,
                ReturnCode = u.ReturnCode,
                Audit = u.Audit,
                ReturnTime = u.ReturnTime,
                IncomingOrdersId = u.IncomingOrdersId,
                IncomingOrdersFkDisplayName = $"{incomingOrders.IncomingNumber}",
                VendorId = u.VendorId,
                VendorFkDisplayName = $"{vendor.VendorCode}",
                Contact = u.Contact,
                ContactInformation = u.ContactInformation,
                DepartmentId = u.DepartmentId,
                DepartmentFkDisplayName = $"{department.DepartmentName}",
                IncomingPeopleId = u.IncomingPeopleId,
                ReturnQuantity = u.ReturnQuantity,
                ReturnedGoods = u.ReturnedGoods,
                UserId = u.UserId,
                UserFkDisplayName = $"{user.UserName}",
                OrganizationsId = u.OrganizationsId,
                OrganizationsFkDisplayName = $"{organizations.OrganizationName}",
                MakeData = u.MakeData,
                Reviewer = u.Reviewer,
                ReviewTime = u.ReviewTime,
                Remarks = u.Remarks,
                UploadFile = u.UploadFile,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取进货退货详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取进货退货详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Returnorders> Detail([FromQuery] QueryByIdReturnordersInput input)
    {
        return await _returnordersRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加进货退货 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加进货退货")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddReturnordersInput input)
    {
        var entity = input.Adapt<Returnorders>();
        return await _returnordersRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新进货退货 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新进货退货")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateReturnordersInput input)
    {
        var entity = input.Adapt<Returnorders>();
        await _returnordersRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除进货退货 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除进货退货")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteReturnordersInput input)
    {
        var entity = await _returnordersRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _returnordersRep.FakeDeleteAsync(entity);   //假删除
        //await _returnordersRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除进货退货 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除进货退货")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteReturnordersInput> input)
    {
        var exp = Expressionable.Create<Returnorders>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _returnordersRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _returnordersRep.FakeDeleteAsync(list);   //假删除
        //return await _returnordersRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 上传上传文件 ⬆️
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [DisplayName("上传上传文件")]
    [ApiDescriptionSettings(Name = "UploadUploadFile"), HttpPost]
    public async Task<SysFile> UploadUploadFile([Required] IFormFile file)
    {
        return await _sysFileService.UploadFile(new UploadFileInput { File = file, SavePath = "upload/Returnorders/UploadFile" }); 
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataReturnordersInput input)
    {
        var incomingOrdersIdData = await _returnordersRep.Context.Queryable<Incomingorders>()
            .InnerJoinIF<Returnorders>(input.FromPage, (u, r) => u.Id == r.IncomingOrdersId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.IncomingNumber}"
            }).ToListAsync();
        var vendorIdData = await _returnordersRep.Context.Queryable<Vendor>()
            .InnerJoinIF<Returnorders>(input.FromPage, (u, r) => u.Id == r.VendorId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.VendorCode}"
            }).ToListAsync();
        var departmentIdData = await _returnordersRep.Context.Queryable<department>()
            .InnerJoinIF<Returnorders>(input.FromPage, (u, r) => u.Id == r.DepartmentId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.DepartmentName}"
            }).ToListAsync();
        var userIdData = await _returnordersRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Returnorders>(input.FromPage, (u, r) => u.Id == r.UserId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        var organizationsIdData = await _returnordersRep.Context.Queryable<Organizations>()
            .InnerJoinIF<Returnorders>(input.FromPage, (u, r) => u.Id == r.OrganizationsId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.OrganizationName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "incomingOrdersId", incomingOrdersIdData },
            { "vendorId", vendorIdData },
            { "departmentId", departmentIdData },
            { "userId", userIdData },
            { "organizationsId", organizationsIdData },
        };
    }
    
    /// <summary>
    /// 导出进货退货记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出进货退货记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageReturnordersInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportReturnordersOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "进货退货导出记录");
    }
    
    /// <summary>
    /// 下载进货退货数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载进货退货数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportReturnordersOutput>(), "进货退货导入模板", (_, info) =>
        {
            if (nameof(ExportReturnordersOutput.IncomingOrdersFkDisplayName) == info.Name) return _returnordersRep.Context.Queryable<Incomingorders>().Select(u => $"{u.IncomingNumber}").Distinct().ToList();
            if (nameof(ExportReturnordersOutput.VendorFkDisplayName) == info.Name) return _returnordersRep.Context.Queryable<Vendor>().Select(u => $"{u.VendorCode}").Distinct().ToList();
            if (nameof(ExportReturnordersOutput.DepartmentFkDisplayName) == info.Name) return _returnordersRep.Context.Queryable<department>().Select(u => $"{u.DepartmentName}").Distinct().ToList();
            if (nameof(ExportReturnordersOutput.UserFkDisplayName) == info.Name) return _returnordersRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            if (nameof(ExportReturnordersOutput.OrganizationsFkDisplayName) == info.Name) return _returnordersRep.Context.Queryable<Organizations>().Select(u => $"{u.OrganizationName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入进货退货记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入进货退货记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportReturnordersInput, Returnorders>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 进货订单编号
                    var incomingOrdersIdLabelList = pageItems.Where(x => x.IncomingOrdersFkDisplayName != null).Select(x => x.IncomingOrdersFkDisplayName).Distinct().ToList();
                    if (incomingOrdersIdLabelList.Any()) {
                        var incomingOrdersIdLinkMap = _returnordersRep.Context.Queryable<Incomingorders>().Where(u => incomingOrdersIdLabelList.Contains($"{u.IncomingNumber}")).ToList().ToDictionary(u => $"{u.IncomingNumber}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.IncomingOrdersId = incomingOrdersIdLinkMap.GetValueOrDefault(e.IncomingOrdersFkDisplayName ?? "");
                            if (e.IncomingOrdersId == null) e.Error = "进货订单编号链接失败";
                        });
                    }
                    // 链接 供应商id
                    var vendorIdLabelList = pageItems.Where(x => x.VendorFkDisplayName != null).Select(x => x.VendorFkDisplayName).Distinct().ToList();
                    if (vendorIdLabelList.Any()) {
                        var vendorIdLinkMap = _returnordersRep.Context.Queryable<Vendor>().Where(u => vendorIdLabelList.Contains($"{u.VendorCode}")).ToList().ToDictionary(u => $"{u.VendorCode}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.VendorId = vendorIdLinkMap.GetValueOrDefault(e.VendorFkDisplayName ?? "");
                            if (e.VendorId == null) e.Error = "供应商id链接失败";
                        });
                    }
                    // 链接 进货部门
                    var departmentIdLabelList = pageItems.Where(x => x.DepartmentFkDisplayName != null).Select(x => x.DepartmentFkDisplayName).Distinct().ToList();
                    if (departmentIdLabelList.Any()) {
                        var departmentIdLinkMap = _returnordersRep.Context.Queryable<department>().Where(u => departmentIdLabelList.Contains($"{u.DepartmentName}")).ToList().ToDictionary(u => $"{u.DepartmentName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.DepartmentId = departmentIdLinkMap.GetValueOrDefault(e.DepartmentFkDisplayName ?? "");
                            if (e.DepartmentId == null) e.Error = "进货部门链接失败";
                        });
                    }
                    // 链接 制单人
                    var userIdLabelList = pageItems.Where(x => x.UserFkDisplayName != null).Select(x => x.UserFkDisplayName).Distinct().ToList();
                    if (userIdLabelList.Any()) {
                        var userIdLinkMap = _returnordersRep.Context.Queryable<UserInfo>().Where(u => userIdLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.UserId = userIdLinkMap.GetValueOrDefault(e.UserFkDisplayName ?? "");
                            if (e.UserId == null) e.Error = "制单人链接失败";
                        });
                    }
                    // 链接 所在部门
                    var organizationsIdLabelList = pageItems.Where(x => x.OrganizationsFkDisplayName != null).Select(x => x.OrganizationsFkDisplayName).Distinct().ToList();
                    if (organizationsIdLabelList.Any()) {
                        var organizationsIdLinkMap = _returnordersRep.Context.Queryable<Organizations>().Where(u => organizationsIdLabelList.Contains($"{u.OrganizationName}")).ToList().ToDictionary(u => $"{u.OrganizationName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.OrganizationsId = organizationsIdLinkMap.GetValueOrDefault(e.OrganizationsFkDisplayName ?? "");
                            if (e.OrganizationsId == null) e.Error = "所在部门链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Returnorders>>();
                    
                    var storageable = _returnordersRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.ReturnCode?.Length > 32, "退货单号长度不能超过32个字符")
                        .SplitError(it => it.Item.Contact?.Length > 32, "联系人长度不能超过32个字符")
                        .SplitError(it => it.Item.IncomingPeopleId?.Length > 32, "进货人长度不能超过32个字符")
                        .SplitError(it => it.Item.ReturnedGoods?.Length > 32, "退货商品长度不能超过32个字符")
                        .SplitError(it => it.Item.Reviewer?.Length > 32, "审核人长度不能超过32个字符")
                        .SplitError(it => it.Item.Remarks?.Length > 32, "备注长度不能超过32个字符")
                        .SplitError(it => it.Item.UploadFile?.Length > 64, "上传文件长度不能超过64个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
